<?php

namespace App\Http\Controllers\Home;

use App\Models\Bonus;
use App\Models\Role;
use App\Repositories\BonusRepository;
use App\Repositories\UsersRepository;
use App\Repositories\WechatRepository;
use App\User;
use App\ZL\Controllers\ApiBaseController;
use App\ZL\Library\Curl;
use App\ZL\Library\ErrorCode;
use App\ZL\ORG\Xcx\Common;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserCenterController extends BaseController
{
    protected $user;
    protected $bonus_repostory;
    protected $wechatRepository;

    public function __construct(UsersRepository $usersRepository, BonusRepository $bonusRepository, WechatRepository $wechatRepository)
    {
        parent::__construct();

        $this->user = $usersRepository;
        $this->bonus_repostory = $bonusRepository;
        $this->wechatRepository = $wechatRepository;
    }

    public function goAuthorize(Request $request)
    {
        $url = request('url');
        if(!$url){
            if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']){
                $url = $_SERVER['HTTP_REFERER'];
            }else{
                dd('没有url');
            }
        }
        $array_query = $request->all();
        $tmp = array();
        foreach($array_query as $k=>$param)
        {
            $tmp[] = $k.'='.$param;
        }
        $params = implode('&',$tmp);
        session(['authorize_before_param'=>$params]);
        session(['authorize_before_url'=>$url]);

        $config_arr = $this->easyOptions;
        //引导用户进入授权页面同意授权，获取code
        $redirect_url = route('wechat.callback');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config_arr['app_id'].'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
//        header("location:$url");
        return redirect($url);
    }

    public function callback(Request $request)
    {
        $config_arr = $this->easyOptions;
        $code = $_GET['code'];
        $state = $_GET['state'];
//        if (empty($code)) $this->error('授权失败');
        //通过code换取网页授权access_token（与基础支持中的access_token不同）
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $config_arr['app_id'] . '&secret=' .  $config_arr['secret'] . '&code=' . $code . '&grant_type=authorization_code';
        $access_token = $token = json_decode(Curl::get($token_url));
        session(['access_token'=>$access_token]);

//        dump(session('access_token'));die;
        //获取openid完毕
        $user = $this->user->checkHasAndSaveGetInfoByWechat($access_token->access_token,$access_token->openid,$access_token->unionid);
        session(['user_id'=>$user->id]);
//        session(['user_id'=>1]);

        $session_id = Str::random(40);
        cache([$session_id => json_encode(['id'=>$user->id])],480);
        $authorize_before_url = session('authorize_before_url');
        $params = session('authorize_before_param');
        $request->session()->forget('authorize_before_url');
        $request->session()->forget('authorize_before_param');
        $url = $authorize_before_url;
        if(!$url)
            $url = "http://mall.hellogreens.cn/web_index/";
        if(strstr($url,'?')===false){
            $url.="?sessionid=".$session_id;
        }else{
            $url.="&sessionid=".$session_id;
        }
        return redirect($url);
    }
}
